package com.javasm.mingming.dynamic.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.javasm.mingming.dynamic.dao.DynamicsDao;
import com.javasm.mingming.dynamic.entity.Dynamics;
import com.javasm.mingming.dynamic.service.DynamicsService;
import com.javasm.mingming.webuser.entity.WebUserInfo;
import com.javasm.mingming.webuser.service.WebUserInfoService;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * (Dynamics)表服务实现类
 *
 * @author makejava
 * @since 2025-01-06 17:31:28
 */
@Service("dynamicsService")
public class DynamicsServiceImpl extends ServiceImpl<DynamicsDao, Dynamics> implements DynamicsService {

    @Resource
    DynamicsDao dynamicsDao;
    @Resource
    WebUserInfoService webUserInfoService;

    @Override
    public PageInfo<Dynamics> getPageInfo(Integer pageNum, Integer pageSize) {
        PageHelper.startPage(pageNum,pageSize);
        LambdaQueryWrapper<Dynamics> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.orderByDesc(Dynamics::getCreateTime);
        List<Dynamics> list = list(queryWrapper);
        //查询 list中 提到的,全部的用户信息,在java中匹配 set进去
        //List<Dynamics> dynamicsList = dynamicsDao.selectAllWithUserInfo();
        //获取 全部的uid集合,集合 不能重复
        Set<Integer> uids = list.stream().map(Dynamics::getUid).collect(Collectors.toSet());
        //用户集合
        List<WebUserInfo> webUserInfoList = webUserInfoService.listByIds(uids);
        //优化一下下面的代码
        /*list.forEach(d ->{
            webUserInfoList.forEach(user ->{
                if (d.getUid().equals(user.getUid())){
                    d.setUserInfo(user);
                }
            });
        });*/
        // 创建一个HashMap来存储用户信息，键为uid，值为WebUserInfo对象
        Map<Integer, WebUserInfo> userInfoMap = webUserInfoList.stream()
            .collect(Collectors.toMap(WebUserInfo::getUid, user -> user));

        // 遍历动态列表，并通过HashMap快速查找用户信息
        list.forEach(d -> {
            Integer uid = d.getUid();
            WebUserInfo userInfo = userInfoMap.get(uid);
            if (userInfo != null) {
                d.setUserInfo(userInfo);
            }
        });


        PageInfo<Dynamics> pageInfo = new PageInfo<>(list);
        return pageInfo;
    }
}

